package com.phpxiu.app.view;

import android.os.Bundle;
import android.os.Message;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.phpxiu.app.adapter.RoomFansRankListAdapter;
import com.phpxiu.app.config.HttpConfig;
import com.phpxiu.app.kkylive.R;
import com.phpxiu.app.model.list.RoomRankFansInfo;
import com.phpxiu.app.model.response.FansRankMode;
import com.phpxiu.app.okhttp.OKHttp;
import com.phpxiu.app.okhttp.handler.OKHttpUIHandler;
import com.phpxiu.app.okhttp.param.OKHttpParam;
import com.phpxiu.app.pulltorefresh.PullToRefreshListView;
import com.phpxiu.app.pulltorefresh.PullToRefreshView;
import com.phpxiu.app.utils.KKYUtil;
import com.phpxiu.app.view.custom.WindowLayout;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by WuJinZhou on 2016/5/30.
 */
public class RoomFansRank extends UIBase implements PullToRefreshView.OnRefreshListener2<ListView>,View.OnClickListener {
    public final static String TAG="RoomFansRank";
    public final static String EXTRA_PARAM_USER_ID_KEY="extra_param_user_id";
    public final static String EXTRA_PARAM_USER_TICKETS_KEY="extra_param_user_tickets";
    public final static int HANDLE_REFRESH_COMPLETE=0x1;
    private WindowLayout mainView;
    private String userId;
    private String tickets;
    private int mOpera= HttpConfig.REQUEST_OPERA_INIT;
    private int pageSize=15;//每页取15条记录
    private int currentAllRecords=0;//当前列表刷新时获取的后台记录条数
    private int pageIndex=1;//下一页序号,页数从1开始计数
    private OKHttpParam param;
    private TextView ticketsCountView;
    private PullToRefreshListView ptrListView;
    private ListView mListView;
    private RelativeLayout listHeadView;
    private AbsListView.LayoutParams headLayoutParam=new AbsListView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
    private RoomFansRankListAdapter mAdapter;
    private List<RoomRankFansInfo>mRanks=new ArrayList<RoomRankFansInfo>();
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        userId=getIntent().getStringExtra(EXTRA_PARAM_USER_ID_KEY);
        if(userId==null||userId.equals("")){
            finish();
            return;
        }
        tickets=getIntent().getStringExtra(EXTRA_PARAM_USER_TICKETS_KEY);
        if(tickets==null||"".equals(tickets)){
            tickets="0";
        }
        setContentView(R.layout.room_fans_rank);
        mainView=(WindowLayout)findViewById(R.id.room_fans_rank_root_view);
        init();
    }

    /**
     * 初始化界面
     */
    private void init(){
        findViewById(R.id.top_bar_back_btn).setOnClickListener(this);
        ptrListView=(PullToRefreshListView)findViewById(R.id.rank_pull_refresh_list_view);
        ptrListView.setOnRefreshListener(this);
        mListView=ptrListView.getRefreshableView();
        mListView.setDivider(null);
        mAdapter=new RoomFansRankListAdapter(this,mRanks);
        listHeadView=(RelativeLayout)LayoutInflater.from(this).inflate(R.layout.room_fans_rank_list_head_view,null);
        ticketsCountView=(TextView)listHeadView.findViewById(R.id.rank_tickets_count_view);
        ticketsCountView.setText(tickets+getString(R.string.ticket_unit));
        listHeadView.setLayoutParams(headLayoutParam);
        mListView.addHeaderView(listHeadView);
        mListView.setAdapter(mAdapter);
        request(mOpera);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.top_bar_back_btn:
                onBackPressed();
                break;
            default:
                break;
        }
    }

    @Override
    public void handleMsg(Message msg) {
        switch (msg.what){
            case HANDLE_REFRESH_COMPLETE:
                if(ptrListView!=null){
                    ptrListView.onRefreshComplete();
                }
                break;
            default:
                break;
        }
    }

    /**
     * 请求初始化排行榜
     */
    private void request(int opera){
        mOpera=opera;
        if(param==null){
            param=OKHttpParam.builder();
            param.put("uid", userId);
            param.put("pageSize",pageSize);
        }
        param.put("pageIndex",1);
        if(mOpera==HttpConfig.REQUEST_OPERA_LOAD){
            param.put("pageIndex",pageIndex==1?2:pageIndex);
        }
        OKHttp.post(HttpConfig.API_GET_FANS_RANK_LIST, param.jsonParam(), TAG, new OKHttpUIHandler(FansRankMode.class) {
            @Override
            public void onSuccess(Object model) {
                FansRankMode m = (FansRankMode) model;
                KKYUtil.log(TAG, "粉丝贡献榜数据：" + m.getResponseStr());
                if (ptrListView != null) {
                    ptrListView.onRefreshComplete();
                }
                List<RoomRankFansInfo> data = m.getData().getLogList();
                if (mOpera == HttpConfig.REQUEST_OPERA_REFRESH || mOpera == HttpConfig.REQUEST_OPERA_INIT) {
                    try {
                        currentAllRecords = Integer.parseInt(m.getData().getTotalItem());
                    } catch (NullPointerException e) {

                    } catch (NumberFormatException e) {

                    }
                    mRanks.clear();
                    pageIndex = 1;
                } else {
                    if (currentAllRecords > 0 && mRanks.size() > 0 && mRanks.size() < currentAllRecords) {
                        pageIndex++;
                    }
                }
                mRanks.addAll(data);
                mAdapter.refresh();
            }

            @Override
            public void onErr(String errMsg) {
                if (ptrListView != null) {
                    ptrListView.onRefreshComplete();
                }
                mainView.showTopMsg(errMsg);
            }
        });
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshView<ListView> refreshView) {
            request(HttpConfig.REQUEST_OPERA_REFRESH);
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshView<ListView> refreshView) {
        if(mRanks.size()!=0&&mRanks.size()<currentAllRecords) {
            request(HttpConfig.REQUEST_OPERA_LOAD);
        }else{
            handler.sendEmptyMessage(HANDLE_REFRESH_COMPLETE);
        }
    }
}
